package com.glela.platform.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.platform.mapper.ProvinceCityAreaMapper;
import com.glela.platform.mapper.UserAddressMapper;
import com.glela.platform.model.Area;
import com.glela.platform.model.City;
import com.glela.platform.model.Province;
import com.glela.platform.model.UserAddress;
import com.glela.platform.model.response.AreaVo;
import com.glela.platform.model.response.CityVo;
import com.glela.platform.model.response.ProvinceVo;
import com.glela.platform.service.UserAddressService;
import com.glela.platform.vo.UserAddressVo;

@Service("userAddressService")
public class UserAddressServiceImpl implements UserAddressService {
	@Autowired
	private RedisUtil				redisUtil;
	@Resource
	private UserAddressMapper		userAddressMapper;
	@Autowired
	private ProvinceCityAreaMapper	provinceCityAreaMapper;

	@Override
	public List<UserAddressVo> listUserAddressPage(long userId, int page, int pageSize) {
		List<UserAddressVo> List = new ArrayList<UserAddressVo>();
		List<UserAddress> UserAddressList = userAddressMapper.selectUserAddressPage(userId, page, pageSize);
		for (UserAddress userAddress : UserAddressList) {
			UserAddressVo userAddressVo = new UserAddressVo();
			userAddressVo.setUserAddressVo(userAddress);
			List.add(userAddressVo);
		}
		return List;
	}

	@Override
	public int addUserAddress(UserAddress userAddress) {
		int i = 0;
		int count = userAddressMapper.selectUserAddressCount(userAddress.getUserId());
		if (count <= 0) {//第一次添加强制为默认
			userAddress.setIsDefault(1);
			i = userAddressMapper.insertUserAddress(userAddress);
		} else {//不是第一次添加
			if (userAddress.getIsDefault() == 1) {//用户要设置新的默认地址
				UserAddress uA = userAddressMapper.selectDefaultAddress(userAddress.getUserId());
				if (null != uA) {//老用户有默认地址。先更新为非默认，然后在插入默认的新地址
					userAddressMapper.updateUserNoIsdefault1(uA.getId(), userAddress.getUserId());
					i = userAddressMapper.insertUserAddress(userAddress);
				} else {//老用户没有默认---新地址就是默认地址
					i = userAddressMapper.insertUserAddress(userAddress);
				}
			} else {//非默认
				i = userAddressMapper.insertUserAddress(userAddress);
			}
		}
		initCacheUserAddress(userAddress.getUserId());
		return i;
	}

	@Override
	public int changeUseraddressByuserId(UserAddress userAddress) {
		int i = userAddressMapper.updateUseraddressByuserId(userAddress);
		if (userAddress.getIsDefault() == 1) {
			userAddressMapper.updateUserNoIsdefault(userAddress.getId(), userAddress.getUserId());
		}
		initCacheUserAddress(userAddress.getUserId());
		return i;
	}

	@Override
	public int removeUseraddressByuserId(long userId, long id) {
		int i = userAddressMapper.deleteUseraddressByuserId(userId, id);
		if (i <= 0) {
			i = 0;
		}
		i = 1;
		initCacheUserAddress(userId);
		return i;
	}

	@Override
	public UserAddressVo selectDefaultAddress(long userId) {
		UserAddress cacheAddress = getDefaultAddress(userId);
		if (cacheAddress != null) {
			return new UserAddressVo(cacheAddress);
		}
		UserAddress userAddress = userAddressMapper.selectDefaultAddress(userId);
		//如果没有默认就返回最近添加的一个地址（对没有默认地址的老用户做兼容处理）
		if (userAddress == null) {
			UserAddress address = userAddressMapper.selectUserAddressorderby(userId);
			if (null != address) {
				initCacheUserAddress(address);
				if (address.getIsDefault() != 1) {
					initCacheUserAddressDefault(userId, address.getId());
				}
				return new UserAddressVo(address);
			}
		} else {
			return new UserAddressVo(userAddress);
		}
		return null;
	}

	@Override
	public UserAddress selectUserAddressById(long id) {
		return userAddressMapper.selectUserAddressById(id);
	}

	@Override
	public UserAddress selectUserAddressById(long userId, long id) {
		UserAddress cacheAddress = getCacheAddress(userId, id);
		if (cacheAddress != null) {
			return cacheAddress;
		}
		UserAddress selectDefaultAddress = selectUserAddressById(id);
		if (selectDefaultAddress != null) {
			initCacheUserAddress(selectDefaultAddress);
			return selectDefaultAddress;
		}
		return null;
	}

	@Override
	public int changeDefaultAddress(long userId, long addressId) {
		if (userAddressMapper.selectJudeUserAddress(userId, addressId) < 1) {
			return 0;
		}
		int updateUserAddressDefault = userAddressMapper.updateUserAddressDefault(userId, addressId);
		initCacheUserAddress(userId);
		return updateUserAddressDefault;
	}

	/** 初始化缓存 */
	private void initCacheUserAddress(long userId) {
		redisUtil.del(RedisKeys.USER_ADDRESS_ + userId);
		redisUtil.hdel(RedisKeys.USER_ADDRESS_DEFAULT, Long.toString(userId));
		List<UserAddress> userAddresses = userAddressMapper.selectAll(userId);
		for (UserAddress userAddress : userAddresses) {
			initCacheUserAddress(userAddress);
		}
	}

	/** 缓存用户地址 */
	private void initCacheUserAddress(UserAddress userAddress) {
		redisUtil.hmset(RedisKeys.USER_ADDRESS_ + userAddress.getUserId(), userAddress.getId().toString(), JSON.toJSONString(userAddress));
		if (userAddress.getIsDefault() == 1) {
			initCacheUserAddressDefault(userAddress.getUserId(), userAddress.getId());
		}
	}

	/** 缓存默认地址 */
	private void initCacheUserAddressDefault(long userId, long addressId) {
		redisUtil.hmset(RedisKeys.USER_ADDRESS_DEFAULT, Long.toString(userId), Long.toString(addressId));
	}

	/** 获取默认地址 */
	private UserAddress getDefaultAddress(long userId) {
		String hget = redisUtil.hget(RedisKeys.USER_ADDRESS_DEFAULT, userId + "");
		if (StringUtils.isNoneBlank(hget)) {
			return getCacheAddress(userId, hget);
		}
		return null;
	}

	/** 从缓存获取地址 */
	private UserAddress getCacheAddress(long userId, long addressId) {
		return getCacheAddress(userId, Long.toString(addressId));
	}

	private UserAddress getCacheAddress(long userId, String addressId) {
		String address_json = redisUtil.hget(RedisKeys.USER_ADDRESS_ + userId, addressId);
		if (StringUtils.isNoneBlank(address_json)) {
			UserAddress parseObject = JSON.parseObject(address_json, UserAddress.class);
			if (parseObject != null) {
				return parseObject;
			}
		}
		return null;
	}

	@Override
	public List<ProvinceVo> provinceCityArea() {
		List<ProvinceVo> voList = new ArrayList<ProvinceVo>();
		List<Province> proList = provinceCityAreaMapper.selectProvinceList();
		if (proList != null && proList.size() > 0) {
			for (Province pro : proList) {
				ProvinceVo pVo = new ProvinceVo();
				BeanUtils.copyProperties(pro, pVo);
				List<City> cityList = provinceCityAreaMapper.selectCityList(pro.getId());
				List<CityVo> citys = new ArrayList<CityVo>();
				if (cityList != null && cityList.size() > 0) {
					for (City city : cityList) {
						CityVo cVo = new CityVo();
						BeanUtils.copyProperties(city, cVo);
						List<Area> areaList = provinceCityAreaMapper.selectAreaList(city.getId());
						List<AreaVo> areas = new ArrayList<AreaVo>();
						if (areaList != null && areaList.size() > 0) {
							for (Area area : areaList) {
								AreaVo aVo = new AreaVo();
								BeanUtils.copyProperties(area, aVo);
								areas.add(aVo);
							}
						}
						cVo.setAreas(areas);
						citys.add(cVo);
					}
				}
				pVo.setCitys(citys);
				voList.add(pVo);
			}

		}
		return voList;
	}

	/**
	 * 根据区划查询
	 */
	@Override
	public List<Map<String, Object>> getZoneByLevelAndParentId(int zongLevel, int parentId) {
		List<Map<String, Object>> zoneList = new ArrayList<Map<String, Object>>();
		if (zongLevel == 1) {
			List<Province> proList = provinceCityAreaMapper.selectProvinceList();
			if (!CollectionUtils.isEmpty(proList)) {
				for (Province province : proList) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", province.getId());
					map.put("name", province.getProName());
					zoneList.add(map);
				}
			}
		} else if (zongLevel == 2) {
			List<City> cityList = provinceCityAreaMapper.selectCityList(parentId);
			if (!CollectionUtils.isEmpty(cityList)) {
				for (City city : cityList) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", city.getId());
					map.put("name", city.getCityName());
					zoneList.add(map);
				}
			}
		} else if (zongLevel == 3) {
			List<Area> areaList = provinceCityAreaMapper.selectAreaList(parentId);
			if (!CollectionUtils.isEmpty(areaList)) {
				for (Area area : areaList) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", area.getId());
					map.put("name", area.getAreaName());
					zoneList.add(map);
				}
			}
		}
		return zoneList;
	}

	/**
	 * 根据银行ID、市ID查询分行
	 */
	@Override
	public Map<String, List<Map<String, Object>>> getBranchBankList(int bankId, int cityId) {
		Map<String, List<Map<String, Object>>> branchBankMap = new HashMap<String, List<Map<String, Object>>>();
		List<Map<String, Object>> branchBankList = this.provinceCityAreaMapper.getBranchBankList(bankId, cityId);
		if (!CollectionUtils.isEmpty(branchBankList)) {
			for (Map<String, Object> bb : branchBankList) {
				List<Map<String, Object>> bbList = new ArrayList<Map<String, Object>>();
				if (branchBankMap.containsKey(bb.get("initials").toString())) {
					bbList = branchBankMap.get(bb.get("initials").toString());
					bbList.add(bb);
					branchBankMap.put(bb.get("initials").toString(), bbList);
				} else {
					bbList.add(bb);
					branchBankMap.put(bb.get("initials").toString(), bbList);
				}
			}
		}
		return branchBankMap;
	}

}
